package http_proxy_middleware

import (
	"strings"

	"gin-gateway/middleware"
	"gin-gateway/core/utils"
	"gin-gateway/core/dao"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
)

// HTTPJwtAuthTokenMiddleware jwt token auth
func HTTPJwtAuthTokenMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		serviceDetail := GetServiceDetail(c)
		if serviceDetail.AccessControl.OpenAuth != 1 { // 没有Auth开启验证
			c.Next()
		}

		// decode jwt token
		// app_id 与  app_list 取得 appInfo
		// appInfo 放到 gin.context
		// --header "Authorization:Bearer eyJhbGci0iJIUzI1NiISInR5cCI6IkpXVCJ9.eyJleHAi0jE10DK2MDI2MjMsImlzcyI6ImFwcF9pZF9iIn0.LOHxcnIF25LAzGqDg0ZzSid0Bp7j-kW4X9_7JuFEx3M"
		JwtToken := strings.ReplaceAll(c.GetHeader("Authorization"), "Bearer ", "")
		if JwtToken == "" {
			middleware.ResponseError(c, 2003, errors.New("jwt validate fail,not match valid app"))
			c.Abort()
			return
		}

		appMatched := false
		claims, err := utils.JwtDecode(JwtToken)
		if err != nil {
			middleware.ResponseError(c, 2002, err)
			c.Abort()
			return
		}
		appInfo, exists := dao.AppManagerHandler.InAppMap(claims.Issuer)
		if exists && appInfo.AppID == claims.Issuer {
			c.Set("app", appInfo)
			appMatched = true
		}

		if !appMatched {
			middleware.ResponseError(c, 2003, errors.New("jwt validate fail,not match valid app"))
			c.Abort()
			return
		}
		c.Next()
	}
}
